package exam.lecode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

/**
 * @version 1.0.0
 * Created by cyd on 2023-03-23 17:37:56
 * @ClassName : exam.lecode.Solution
 * @Description : 两数之和
 */
public class Solution {
    public static void main(String[] args) {
//        nums = [2,7,11,15]
        int[] nums = new int[]{20, 70, 110, 150};
        int target = 90;
        int[] ints = twoSumByHashMap2(nums, target);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] twoSum(int[] nums, int target) {
        int[] resultArr = new int[2];
        int result;

        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                result = nums[i] + nums[j];
                if (target == result) {
                    resultArr[0] = i;
                    resultArr[1] = j;
                }
            }
        }
        return resultArr;
    }

    /**
     * map中的 key:数组中的值，value：数组中的值对应的下标
     *
     * @param nums   目标数组
     * @param target 目标数
     * @return 答案数组
     */
    public static int[] twoSumByHashMap(int[] nums, int target) {
        int[] resArr = new int[2];
        if (nums == null || nums.length == 0) {
            return resArr;
        }
        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
            int temp = target - nums[i];
            if (map.containsKey(temp)) {
                resArr[1] = i + 1;
                resArr[0] = map.get(temp) + 1;
            }
        }
        return resArr;
    }

    public static int[] twoSumByHashMap2(int[] numbers, int target) {
        int[] resArr = new int[2];
        if (numbers == null || numbers.length == 0) {
            return resArr;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            map.put(numbers[i], i);
        }

        int temp;
        for (int i = 0; i < numbers.length; i++) {
            temp = target - numbers[i];
            if (map.containsKey(temp) && map.get(temp) != i) {
                resArr[0] = i + 1;
                resArr[1] = map.get(temp) + 1;
            }
        }
        resArr = Arrays.stream(resArr).sorted().toArray();
        return resArr;
    }
}
